package com.wxy.netty.黏包半包处理;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 47868
 */
public class Server {
    public static void main(String[] args) {
        new ServerBootstrap()
                .group(new NioEventLoopGroup(),new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                //调整系统的接收缓冲器(滑动窗口) 设置过大会黏包 过小会半包
                //.option(ChannelOption.SO_RCVBUF, 5)
                //调整netty的接收缓冲区 byteBuf
                .childOption(ChannelOption.RCVBUF_ALLOCATOR,new AdaptiveRecvByteBufAllocator(10,10,10))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf byteBuf = (ByteBuf) msg;
                                System.out.println(byteBuf);
                                while (byteBuf.readableBytes()>0) {
                                    System.out.print(byteBuf.readByte()+" ");
                                }
                                System.out.println("\n"+"-----------------------------------");
                                super.channelRead(ctx, msg);
                            }
                        });
        }
                })
                .bind("127.0.0.1",8888);
    }
}
